import React from 'react';
import {Menu, Dropdown, Icon, Checkbox, Select} from 'antd';
import {ALL_DEVICE, defaultDeviceListFilter, typeMap} from "../config/const";
import {connect} from "react-redux";
import {CHANGE_DEVICES_VISIBILITY} from "../models/device/const";

const Option = Select.Option;

@connect(({device,}) => ({
  deviceListFilter: device.deviceListFilter,
}),)
class DeviceTypeSelect extends React.Component {
  handleCheckChange = (e) => {
    const {value, checked} = e.target;
    const {deviceListFilter, dispatch} = this.props;
    if (value === ALL_DEVICE) {
      dispatch({
        type: CHANGE_DEVICES_VISIBILITY,
        payload: checked ? defaultDeviceListFilter : []
      })
    } else {
      dispatch({
        type: CHANGE_DEVICES_VISIBILITY,
        payload: checked ? [value, ...deviceListFilter] : deviceListFilter.filter(item => item !== value)
      })
    }
  };

  handleSelectChange = (value) => {
    const {dispatch} = this.props;
    if (value === ALL_DEVICE) {
      dispatch({
        type: CHANGE_DEVICES_VISIBILITY,
        payload: defaultDeviceListFilter
      })
    } else {
      dispatch({
        type: CHANGE_DEVICES_VISIBILITY,
        payload: [value]
      })
    }
  };

  render() {
    const {deviceListFilter, isFormItem} = this.props;
    return (
      isFormItem ? <div>
          设备类型:
          <Select value={deviceListFilter.length > 1 ? ALL_DEVICE : deviceListFilter[0]} style={{width: 120}}
                  onChange={this.handleSelectChange}>
            {[ALL_DEVICE, ...defaultDeviceListFilter].map(
              item => (
                <Option key={item} value={item}>{typeMap[item] || '全选'}</Option>
              )
            )}
          </Select>
        </div> :
        <Dropdown overlay={
          <Menu>
            {['-1','0','1','2'].map(
              item => (
                <Menu.Item key={item}>
                  <Checkbox
                    value={item}
                    onChange={this.handleCheckChange}
                    checked={item === ALL_DEVICE ? deviceListFilter.length === defaultDeviceListFilter.length : deviceListFilter.includes(item)}
                  >
                    {typeMap[item] || '显示总设备'}
                  </Checkbox>
                </Menu.Item>
              )
            )}
          </Menu>
        }
        >
          <a className="dropdown-link" href="#">
            <Icon type="down"/>
          </a>
        </Dropdown>
    )
  }
}


export default DeviceTypeSelect;
